﻿using System.Collections.Generic;

namespace Honeycomb.Core
{
    /// <summary>
    /// A thread safe queue implementation.
    /// </summary>
    /// <typeparam name="TType">Type of elements in the Queue.</typeparam>
    public class Queue<TType>
    {
        /// <summary>
        /// A LinkedList is used for performance reasons.
        /// </summary>
        protected readonly LinkedList<TType> queue = new LinkedList<TType>();

        /// <summary>
        /// Dequeues the top element in the queue and returns it. If the queue 
        /// is empty the method returns default (TType).
        /// </summary>
        /// <returns>The first element in the queue, or default (TType) if queue is empty.</returns>
        public virtual TType Dequeue()
        {
            lock (queue)
            {
                if (queue.Count == 0)
                    return default(TType);

                TType value = queue.First.Value;
                queue.RemoveFirst();
                return value;
            }
        }

        /// <summary>
        /// Enqueues an element to the queue and returns the length of the 
        /// queue.
        /// </summary>
        /// <param name="value">Value to enqueue.</param>
        /// <returns>Queue length after enqueue.</returns>
        public virtual int Enqueue(TType value)
        {
            lock (queue)
            {
                queue.AddLast(value);
                return queue.Count;
            }
        }
    }
}